﻿using NLog;
using System;
using System.Linq;
using System.Globalization;
using Microsoft.SharePoint;
using SharePoint.Utility.Logging;

namespace CopyOrdersList.BL.Helpers
{
    public class ListHelper
    {
        static ILogger logger = DetailLog.GetLogger;

        public static SPList CreateNewListAsSourceList(SPList sourceList, SPWeb web) {
            var template = getListTemlateDefinition(web, sourceList.TemplateFeatureId, sourceList.BaseTemplate);
            string title = sourceList.RootFolder.Name +"_NewList";
            string description = sourceList.Description;
            Guid guid = CreateList(web, title, description, template);            
            SPList newList = web.Lists.GetList(guid, false);
            copyTitleResources(sourceList, newList);
            RenameSourceList(sourceList, newList);
            newList.Update();
            sourceList.Update();
            return newList;
        }

        public static SPListTemplate getListTemlateDefinition(SPWeb web, Guid featureId, SPListTemplateType templateType)
        {
            return web.ListTemplates.OfType<SPListTemplate>().FirstOrDefault(t => t.FeatureId == featureId && t.Type == templateType);
        }

        public static void RenameSourceList(SPList sourceList, SPList newList) {
            using (DisabledItemEventsScope disableEvents = new DisabledItemEventsScope()) {
                try {
                    sourceList.RootFolder.MoveTo(sourceList.RootFolder.Url + "_Old");
                    newList.RootFolder.MoveTo(newList.RootFolder.Url.Replace("_NewList", ""));
                }
                catch (Exception ex) {
                    logger.Error(ex.ToString());
                }
            }
        }

        private static Guid CreateList (SPWeb web, string title, string description, SPListTemplate template){
            try {
                return web.Lists.Add(title, description, template);
            }
            catch(Exception ex) {
                throw ex;
            }
        }

        private static void copyTitleResources(SPList sourceList, SPList newList) {
            foreach (CultureInfo c in sourceList.ParentWeb.SupportedUICultures) {
                newList.TitleResource.SetValueForUICulture(c, sourceList.TitleResource.GetValueForUICulture(c));
                newList.Update();
            }
        }

        public static SPList getListByUrl(SPWeb web, string listUrl){
           try {
               return web.GetList(web.ServerRelativeUrl + "/lists/" + listUrl);
           }
           catch (Exception ex) {
               logger.Error("List " + listUrl + " was not found", ex.Message.ToString());
               throw ex;
           }
        }
    }
}
